//
//  AuthorManager.m
//  ZYYD
//
//  Created by yuzhou on 12-8-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AuthorManager.h"
#import <CommonCrypto/CommonDigest.h>
#import "GTMBase64.h"
//#import "GlobalVariry.h"

@implementation NSString (md5)

- (NSString *)MD5Base64String
{
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5([[self dataUsingEncoding:NSUTF8StringEncoding] bytes], [self length], result);
    NSData *data = [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH];
    data = [GTMBase64 encodeData:data];
    NSString * base64String = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
    return base64String;
}
@end

@implementation AuthorManager
@synthesize userInfo,userID,tempPassword,tempUserName,tempEmail;

static AuthorManager *authorManager;
+ (id)defaultManager
{
    if (authorManager) {
        return authorManager;
    }
    authorManager = [[AuthorManager alloc] init];
    return authorManager;
}

- (id)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readAuthorityFail) name:kReadAuthorityFail object:nil];
    }
    return self;
}

- (NSString *)userID
{
//    if (!loggedIn) {
//        return @"";
//    }
//    return [userInfo valueForKey:@"user_id"];
    return @"999920";
}

- (NSString *)username
{
    if (!loggedIn) {
        return @"";
    }
    return [userInfo valueForKey:@"user_name"]?[userInfo valueForKey:@"user_name"]:[userInfo valueForKey:@"username"];
}

- (NSString *)email
{
    //    if (![self hasLoggedInRequired:YES]) {
    //        return nil;
    //    }
    return [userInfo valueForKey:@"email"];
}

- (NSString *)tempUserName
{
//    if (![self hasLoggedInRequired:YES]) {
//        return nil;
//    }
    return tempUserName;
}

- (NSString *)tempEmail
{
//    if (![self hasLoggedInRequired:YES]) {
//        return nil;
//    }
    return tempEmail;
}

- (NSString *)sessionID
{
    return nil;
}

- (BOOL)hasLoggedInRequired:(BOOL)required
{
    if (![self hasLoggedIn] && required) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginRequired object:nil];
    }
    return [self hasLoggedIn];
}

- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    self.tempUserName = username;
    self.tempPassword = password;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] loginWithUsername:username password:[password MD5Base64String]];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *result = [obj objectForKey:@"result"];
            
            if ([[result objectForKey:@"success"] isEqualToString:@"true"]) {
                loggedIn = YES;
                self.userInfo = result;
                [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccess object:nil];
                
                //下次启动自动登录
                [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"auto_login"];
                [[NSUserDefaults standardUserDefaults] setObject:tempUserName forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] setObject:tempPassword forKey:@"password"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            else {
                [[NSNotificationCenter defaultCenter] postNotificationName: kLoginFail object:nil];
            }

        });
    });
}

- (void)loginResult:(NSNotification *)notification
{
    NSDictionary *result = [notification.object valueForKey:@"result"];
    
    if ([[result valueForKey:@"success"] isEqualToString:@"true"]) {
        loggedIn = YES;
        self.userInfo = result;
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccess object:nil];
        
        //下次启动自动登录
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"auto_login"];
        [[NSUserDefaults standardUserDefaults] setObject:tempUserName forKey:@"username"];
        [[NSUserDefaults standardUserDefaults] setObject:tempPassword forKey:@"password"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else {
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginFail object:nil];
    }
}

- (void)logOut
{
    loggedIn = NO;
    self.userInfo = nil;
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"auto_login"];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"password"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [[NSNotificationCenter defaultCenter] postNotificationName:kLogout object:nil];
}

- (void)registerWithUsername:(NSString *)username password:(NSString *)password email:(NSString *)email
{
    self.tempUserName = username;
    self.tempPassword = password;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] registerWithUsername:username password:[password MD5Base64String] email:email];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *result = [obj objectForKey:@"result"];
            self.userInfo = result;
            if ([[result valueForKey:@"success"] isEqualToString:@"true"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kRegisterSuccess object:nil];
                [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"auto_login"];
                [[NSUserDefaults standardUserDefaults] setObject:tempUserName forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] setObject:tempPassword forKey:@"password"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            else {
                [[NSNotificationCenter defaultCenter] postNotificationName:kRegisterFail object:nil];
            }
        });
    });
}

- (void)registerResult:(NSNotification *)notification
{
    NSDictionary *result = [notification.object valueForKey:@"result"];
    
    if ([[result valueForKey:@"success"] isEqualToString:@"true"]) {
        loggedIn = YES;
        self.userInfo = result;
//        [[NSNotificationCenter defaultCenter] postNotificationName:kRegisterSuccess object:nil];
        
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"auto_login"];
        [[NSUserDefaults standardUserDefaults] setObject:tempUserName forKey:@"username"];
        [[NSUserDefaults standardUserDefaults] setObject:tempPassword forKey:@"password"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else {
//        [[NSNotificationCenter defaultCenter] postNotificationName:kRegisterFail object:nil];
    }
}

- (BOOL)hasLoggedIn
{
    return loggedIn;
}

- (BOOL)hasUserPaid
{
    return loggedIn && [[userInfo valueForKey:@"read_limit"] boolValue];
}

- (void)readAuthorityFail
{
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未激活" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil] autorelease];
    [alertView show];
    
}
- (void)modifyPasswordWithOriginPassword:(NSString *)originPassowrd newPassword:(NSString *)newPassword{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary * obj = [[DataRequest sharedRequest]modifyPasswordWithOriginPassword:[originPassowrd MD5Base64String] newPassword:[newPassword MD5Base64String]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString * cussessStr = [[obj objectForKey:@"result"] objectForKey:@"success"];
            if ([cussessStr isEqualToString:@"true"]) {
                [[NSUserDefaults standardUserDefaults] setObject:newPassword forKey:@"password"];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:Kmodify object:cussessStr];
            
        });
    });
}
- (void)modifyTelNumber:(NSString *)telNumber password:(NSString *)password{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] modifyTelNumber:telNumber password:[password MD5Base64String]];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString * str = [[obj objectForKey:@"result"] objectForKey:@"status_message"];
            [[NSNotificationCenter defaultCenter] postNotificationName:KmodifyTel object:str];
        });

    });
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [userInfo release];
    [userID release];
    [tempUserName release];
    [tempPassword release];
    [tempEmail release];
    
    [super dealloc];
}
@end
